import axios from "axios";
import { Message, Notification } from "element-ui";
import { COURSE_API_HOST } from "@/plugins/config";

const config = {
  baseURL: COURSE_API_HOST,
  timeout: 60 * 1000
};

// 控制每次只展示一条message
let messageInstance = null;
const noticeError = (msg) => {
  if (!msg) return;
  if (messageInstance) {
    messageInstance.closeAll();
  }
  messageInstance = Message({
    message: msg,
    type: "error",
    duration: 2 * 1000,
    onClose: () => {
      messageInstance = null;
    }
  });
};

const instance = axios.create(config);

// 设置拦截器，手动添加cookie
instance.interceptors.request.use((config) => {
  return config;
});

// 对响应数据进行处理
instance.interceptors.response.use(
  (response) => {
    const { noticeMessage } = response.config;
    const { code } = response.data || {};
    switch (code) {
      case undefined:
        return response.data; // 兼容老接口
      case 1:
        return response.data.result || response.data; // 兼容返回值无result的情况
      default:
        if (noticeMessage !== false) {
          noticeError(response.data.message)
        }
        return Promise.reject(response.data);
    }
  },
  (error) => {
    if (error && error.response) {
      let errorMsg = "";
      switch (error.response.status) {
        case 500:
          errorMsg = error.response.data.message;
          break;
        case 400:
          errorMsg = "请求错误！";
          break;
        case 401:
          errorMsg = "登录信息过期！";
          break;
        case 403:
          errorMsg = "拒绝访问";
          break;
        default:
          console.error(error.response);
          break;
      }
      noticeError(errorMsg);
    }
  }
);

export default instance;
